package com.googlecode.maven.plugin.appassembler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * ZIP (.zip) archiver.
 */
public class ZipArchiver
        extends AbstractArchiver
    {
    /**
     * {@inheritDoc}
     */
    public void archive(File sourceDirectory, File targetFile,
            List<String> executableFiles)
            throws IOException
        {
        OutputStream ostrm = null;
        try
            {
            ostrm = new FileOutputStream(targetFile);
            ZipOutputStream zostrm = null;
            try
                {
                zostrm = new ZipOutputStream(ostrm);
                for (File file : FileUtils.
                        listFiles(sourceDirectory, null, true))
                    {
                    if (file.isFile())
                        {
                        String path = getRelativePath(sourceDirectory, file);
                        zostrm.putNextEntry(new ZipEntry(path));
                        InputStream istrm = null;
                        try
                            {
                            istrm = new FileInputStream(file);
                            IOUtils.copy(istrm, zostrm);
                            }
                        finally
                            {
                            IOUtils.closeQuietly(istrm);
                            }
                        }
                    }
                }
            finally
                {
                IOUtils.closeQuietly(zostrm);
                }
            }
        finally
            {
            IOUtils.closeQuietly(ostrm);
            }
        }
    }
